package com.gh.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.gh.util.ConstantPropertiesUtils;
import com.gh.common.exception.BusinessException;
import com.gh.common.result.ResponseEnum;
import com.gh.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author Eric
 * @Date 2021/9/11 9:36
 * @Version 1.0
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Override
    public boolean sendCode(Map<String, Object> map, String phone) {

        DefaultProfile profile = DefaultProfile.getProfile(ConstantPropertiesUtils.REGION_ID, ConstantPropertiesUtils.ACCESS_KEY_ID, ConstantPropertiesUtils.SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", ConstantPropertiesUtils.REGION_ID);
        // 发给谁  ----
        request.putQueryParameter("PhoneNumbers", phone);
        // 签名名称
        request.putQueryParameter("SignName", "薄荷园项目");
        // 模板名称
        request.putQueryParameter("TemplateCode", "SMS_171857472");
        // 验证码 ----
        //request.putQueryParameter("TemplateParam", "{\"code\":\"" + map.get("code") + "\"}");
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map).toString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            log.info(response.getData());
            return success;
        } catch (ServerException e) {
            log.error("阿里云短信发送失败" + e.getErrCode() + "," + e.getErrMsg());
            e.printStackTrace();
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
